package com.vcredit.creditcat.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class EncoderHandler {

	/**
	 * 
	 * 生成 64位编码
	 * 
	 * @param contents
	 * 
	 * @param width
	 * 
	 * @param height
	 * 
	 * @param imgPath
	 * 
	 */

	public String encode(String contents, int width, int height, String imgPath) throws Exception {

		Hashtable<Object, Object> hints = new Hashtable<Object, Object>();
		// 指定纠错等级
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		// 指定编码格式
		try {

			BitMatrix byteMatrix;
			byteMatrix = new MultiFormatWriter().encode(new String(contents.getBytes("UTF-8"), "iso-8859-1"),
					BarcodeFormat.QR_CODE, width, height);
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			MatrixToImageWriter.writeToStream(byteMatrix, "png", bao);
			String ok = Base64Code(bao.toByteArray());
			System.out.println(ok);
			return ok;
			/* createImage(ok); */

		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;

	}

	public String Base64Code(byte[] b) throws Exception {
		BASE64Encoder encoder = new BASE64Encoder();
		String codeBase64 = "";
		StringBuilder pictureBuffer = new StringBuilder();
		pictureBuffer.append(encoder.encode(b));
		// System.out.println(pictureBuffer.toString());
		codeBase64 = pictureBuffer.toString();
		return codeBase64;
	}

	/**
	 * 创建图片
	 * 
	 * @param Base64
	 * @throws Exception
	 */
	public void createImage(String Base64) throws Exception {
		BASE64Decoder decoder = new BASE64Decoder();
		FileOutputStream write;
		try {
			write = new FileOutputStream(new File("D:/ok.png"));
			byte[] decoderBytes = decoder.decodeBuffer(Base64);
			write.write(decoderBytes);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Decoding the picture Success");
	}

	/**
	 * 
	 * @param args
	 * 
	 */

	/*public static void main(String[] args) throws Exception {

		String imgPath = "e:/zxing.png";

		String contents = "http://www.baidu.com";

		int width = 300, height = 300;

		EncoderHandler handler = new EncoderHandler();

		handler.encode(contents, width, height, imgPath);
		System.out.println("successful");

	}*/

}